package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //判断购物车是否为空
        ShoppingCart shoppingCart = new ShoppingCart();
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //判断地址簿是否为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

//1.向订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        //时间戳实现订单编号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
//2.向订单明细表插入数据
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);
        orders.setAddress(addressBook.getDetail());
        String name = userMapper.getByUserId(userId);
        orders.setUserName(name);
        orderMapper.insert(orders);
//3.向订单明细表插入n条数据
        //封装数据
        //插入数据批量插入
        List<Object> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
//向订单明细表批量插入数据
        orderDetailMapper.insertBatch(orderDetailList);
//清空当前购物车
        shoppingCartMapper.deleteAll(userId);

        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setId(orders.getId());

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
 /*       // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

       *//* JSONObject jsonObject = new JSONObject();//自己添加的内容*//*
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));*/
        //自己修改
            OrderPaymentVO vo = new OrderPaymentVO();
            vo.setNonceStr("666");
            vo.setPaySign("hhh");
            vo.setPackageStr("prepay_id=wx");
            vo.setSignType("RSA");
            vo.setTimeStamp("1670380960");
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //通过websocket向客户端浏览器推送消息 type order_id cotent
        Map map = new HashMap();
        map.put("type",1);//1.来单提醒 2.客户催单
        map.put("order_id",ordersDB.getId());
        map.put("content","订单号: " + outTradeNo);
        String json = JSON.toJSONString(map);
       webSocketServer.sendToAllClient(json);
      /*  //自己添加内容
        HashMap<Object, Object> map = new HashMap<>();
        map.put("type",1);
        map.put("orderId", ordersDB.getId());
        map.put("content","订单号: " + outTradeNo);
        String json = JSONObject.toJSONString(map);
        WebSocketServer webSocketServer = new WebSocketServer();
        webSocketServer.sendToAllClient(json);*/
    }
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList<>();
        //将数据封装入list
        if (page != null && page.size()>0) {

            for (Orders orders : page) {
                //查询订单明细表
                Long orderId = orders.getId();
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOderId(orderId);
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                list.add(orderVO);
            }
        }
PageResult pageResult = new PageResult(page.getTotal(),list);

        return pageResult;
    }

    /**
     * 根据订单id查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO selectOrderDetail(Long id) {
        Orders orders= orderMapper.getOrderById(id);
        OrderVO orderVO = new OrderVO();
BeanUtils.copyProperties(orders,orderVO);
List<OrderDetail> orderDetailList = orderDetailMapper.getByOderId(id);
orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }
    /**
     * 取消订单
     */
    @Override
    public void cancel(Long id) {
        //取消订单可以直接取消
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CANCELLED);
        orderMapper.update(orders);

    }

    /**
     * 接单
     * @param
     */
    @Override
    public void acceptOrder(OrdersConfirmDTO ordersConfirmDTO) {

        Orders orders = Orders.builder()
                .status(Orders.CONFIRMED)
                .id(ordersConfirmDTO.getId())
                .build();
        orderMapper.update(orders);
    }

    @Override
    public OrderStatisticsVO statisticOrders() {
        //待接单
        Integer  toBeConfirmed  = orderMapper.countOrders(Orders.TO_BE_CONFIRMED);
        //带派送
        Integer confirmed = orderMapper.countOrders(Orders.CONFIRMED);
        //派送中
        Integer deliveryInProgress= orderMapper.countOrders(Orders.DELIVERY_IN_PROGRESS);
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);

        return orderStatisticsVO;
    }

    /**
     * 拒单
     * * @param ordersRejectionDTO
     * @throws Exception
     */
    @Override
    public void rejectOrders(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        Orders orders = new Orders();
        //商家拒单其实就是将订单状态修改为“已取消”

        //1.判断订单是否处于，待接单状体
        Orders orderDB = orderMapper.getOrderById(ordersRejectionDTO.getId());
        if (orderDB.getStatus() != Orders.TO_BE_CONFIRMED || orderDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //支付状态
        Integer payStatus = orderDB.getPayStatus();
/*        // 商家拒单时，如果用户已经完成了支付，需要为用户退款
if (payStatus == Orders.PAID){
    //用户已支付，需要退款
    String refund = weChatPayUtil.refund(
            orderDB.getNumber(),
            orderDB.getNumber(),
            new BigDecimal(0.01),
            new BigDecimal(0.01));
    log.info("申请退款：{}", refund);
}*/
// 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
    orders.setId(orderDB.getId());
    orders.setStatus(Orders.CANCELLED);
    orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
    orders.setCancelTime(LocalDateTime.now());
orderMapper.update(orders);
    }
    @Override
    public void cancelOrder(OrdersCancelDTO ordersCancelDTO) {
        /**
         * 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
         */
        //接单以后才有取消功能，修改状态为已取消
        Orders order = orderMapper.getOrderById(ordersCancelDTO.getId());
        //判断订单状态，处于待派送(已经接单)，还是待付款
        Integer payStatus = order.getPayStatus();
    /*    if (payStatus == 1) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    order.getNumber(),
                    order.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }*/
        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(order.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }
    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders order = orderMapper.getOrderById(id);
        if (order ==null || order.getStatus() != Orders.CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(order.getId());
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
     orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void completeOrder(Long id) {
        //判断订单是否是派送中，若在派送中则修改订单为已完成
        Orders order = orderMapper.getOrderById(id);
        if (order.getStatus() == null || order.getStatus() != Orders.DELIVERY_IN_PROGRESS){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(order.getId());
        orders.setStatus(Orders.COMPLETED);
        orderMapper.update(orders);
    }

    /**
     * 用户取消订单
     * @param id
     */
    @Override
    public void userCancel(Long id) {
              /* -待支付和待接单状态下，用户可直接取消订单
                - 商家已接单状态下，用户取消订单需电话沟通商家
                - 派送中状态下，用户取消订单需电话沟通商家
                - 如果在待接单状态下取消订单，需要给用户退款
                - 取消订单后需要将订单状态修改为“已取消”*/
        Orders order = orderMapper.getOrderById(id);
        if (order.getStatus() == null){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        if (order.getStatus() > 2 ){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        if (order.getStatus() == Orders.TO_BE_CONFIRMED){
            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setId(id);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOderId(id);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }
    /**
     * 催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        //校验订单是否存在
        Orders order = orderMapper.getOrderById(id);
        if (order.getStatus() == null){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Map map = new HashMap();
        map.put("type",2);//1.表示来单提醒 2.客户催单
        map.put("orderId",id);
        map.put("content","订单号：" + order.getNumber());
        //向客户端浏览器推送消息
webSocketServer.sendToAllClient(JSON.toJSONString(map));


    }
}
